import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  productListApi,
  productStoreApi,
  productUpdateApi,
  productDeleteApi,
  productShowApi,
  categorySelectApi
} from "@/api/quotedPriceApi";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    keyword: "",
    type: "",
    dateRange: [],

  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const categoryOption = ref([
    {id: 1, name: '设备'},
    {id: 2, name: '配件'},
    {id: 3, name: '产品'},
  ])
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "id",
      width: 60
    },
    {
      label: "设备名称",
      prop: "deviceName"
    },

    {
      label: "设备类型",
      prop: "deviceTypeName"
    },
    {
      label: "设备单位",
      prop: "deviceUnit"
    },
    {
      label: "品牌",
      prop: "brand",
      formatter: (row) => {
        return row.brand?.brandName ?? '--';
      }
    },
    {
      label: "供应商",
      prop: "supplier",
      formatter: (row) => {
        return row.supplier?.supplierName ?? '--';
      }
    },
    {
      label: "来源类型",
      prop: "originType",
      formatter: (row) => {
        return row.originType === 1? '自制' : '外购';
      }
    },
    {
      label: "国产/进口",
      prop: "isForeign",
      formatter: (row) => {
        return row.isForeign === 0? '国产' : '进口';
      }
    },
    {
      label: "价格",
      prop: "price",
      formatter: (row) => {
        return row.price || '--';
      }
    },
    {
      label: "长/宽/高",
      prop: "specLength",
      formatter: (row) => {
        return (row.specLength ?? '--') +'/'+ (row.specWidth ?? '--') +'/'+ (row.specHeight ?? '--');
      }
    },
    {
      label: "角度",
      prop: "specAngle",
      formatter: (row) => {
        return row.specAngle || '--';
      }
    },
    {
      label: "功率",
      prop: "power",
      formatter: (row) => {
        return row.power || '--';
      }
    },
    {
      label: "速度",
      prop: "speed",
      formatter: (row) => {
        return row.speed || '--';
      }
    },
    {
      label: "效率",
      prop: "efficiency",
      formatter: (row) => {
        return row.efficiency || '--';
      }
    },
    {
      label: "最大载重",
      prop: "maxLoad",
      formatter: (row) => {
        return row.maxLoad || '--';
      }
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 140
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    const res: any = await productListApi(toRaw(form));
    dataList.value = res?.result.list;
    pagination.total = res?.result.total;
    pagination.pageSize = res?.result.perPage*1;


    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.keyword = "";
    form.type = "";
    form.dateRange = [];
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  async function openDialog(title = "创建设备", row?: FormItemProps) {

    let formInline = {
      title: title,
      id: row?.id ?? null,
      origin: row?.origin ?? null,
      partList: [{part: null}],
      deviceType: 1,
      deviceName: null,
      deviceUnit: null,
      originType: null,
      isForeign: null,
      part: null,
      price: null,
      brandId: null,
      supplierId: null,
      specLength: null,
      specWidth: null,
      specHeight: null,
      specAngle: null,
      power: null,
      speed: null,
      efficiency: null,
      maxLoad: null,
      rollerInterval: null,
      craft: null,
      driveMethod: null,
      metalMaterial: null,
      rollerDiameter: null,
      categoryId: null,
      deviceId: null,
      categoryList: [],
      categoryOption: categoryOption.value,
      code: null
    };
    const category: any = await categorySelectApi({
      type: 1
    })
    formInline.categoryList = category?.result
    if (title === "编辑设备") {
      const res: any = await productShowApi({
        deviceId: row.id
      });

      formInline.deviceId = res?.result?.id;
      formInline.deviceType = res?.result?.deviceType;
      formInline.deviceName = res?.result?.deviceName;
      formInline.deviceUnit = res?.result?.deviceUnit;
      formInline.originType = res?.result?.originType;
      formInline.isForeign = res?.result?.isForeign;
      formInline.part = res?.result?.part;
      formInline.price = res?.result?.price;
      formInline.brandId = res?.result?.brandId;
      formInline.supplierId = res?.result?.supplierId;
      formInline.specLength = res?.result?.specLength;
      formInline.specWidth = res?.result?.specWidth;
      formInline.specHeight = res?.result?.specHeight;
      formInline.specAngle = res?.result?.specAngle;
      formInline.power = res?.result?.power;
      formInline.speed = res?.result?.speed;
      formInline.efficiency = res?.result?.efficiency;
      formInline.maxLoad = res?.result?.maxLoad;
      formInline.rollerInterval = res?.result?.rollerInterval;
      formInline.craft = res?.result?.craft;
      formInline.driveMethod = res?.result?.driveMethod;
      formInline.metalMaterial = res?.result?.metalMaterial;
      formInline.rollerDiameter = res?.result?.rollerDiameter;
      formInline.categoryId = res?.result?.deviceType;
      formInline.code = res?.result?.code;

    } else {

    }

    addDialog({
      title: title,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "700px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            let params = {
              deviceId: curData.id,
              deviceType: curData.deviceType,
              deviceName: curData.deviceName,
              deviceUnit: curData.deviceUnit,
              originType: curData.originType,
              isForeign: curData.isForeign,
              part: curData.part,
              price: curData.price.toFixed(2),
              brandId: curData.brandId,
              supplierId: curData.supplierId,
              specLength: curData.specLength,
              specWidth: curData.specWidth,
              specHeight: curData.specHeight,
              specAngle: curData.specAngle,
              power: curData.power,
              speed: curData.speed,
              efficiency: curData.efficiency,
              maxLoad: curData.maxLoad,
              rollerInterval: curData.rollerInterval,
              craft: curData.craft,
              driveMethod: curData.driveMethod,
              metalMaterial: curData.metalMaterial,
              rollerDiameter: curData.rollerDiameter,
              categoryId: curData.deviceType,
              code: curData.code,
            }
            if (title === "创建设备") {
              productStoreApi(cleanEmptyData(params)).then((res) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              productUpdateApi(cleanEmptyData(params)).then((res) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    ElMessageBox.confirm('确定继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      productDeleteApi({ productId: row.id }).then((res) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
  };
}
